<?php
/**
 * function_common.php
 * 网站常用函数
 * 
 * @author  王中艺
 * @date    2016-02-16
 */

/**
 * 对存入cookie中的值进行base64编码
 *
 * @param $name
 * @param string $value
 * @return mixed|null|string
 */
function safe_cookie($name, $value='', $expire = 7*3600*24) {
    if(empty($name)) {
        return NULL;
    }
    if(!empty($value)) {
        $value  = json_encode($value);
        $value  = think_encrypt($value);
        cookie($name, $value, $expire);
    }else if($value === null){
        cookie($name, null);
    }else{
        $value = cookie($name);
        $value = think_decrypt($value);
        $value = json_decode($value, true);
        return $value;
    }
}

/**
 * 手机号验证
 * @param   $phone
 * @return boolen
 */
function is_phone($phone){
    if(preg_match('/^1[0-9]{10}$/',$phone))
        return true;

    return false;
}

/**
 * @param   $bankCard
 * @return  boolen
 */
function is_bank_card($bankCard){
    if(is_numeric($bankCard) && strlen($bankCard) >= 15)
        return true;

    return false;
}

/**
 * 文件上传
 * @param   $file
 * @return  $src
 */
function upload_file(){
    if(empty($_FILES))
        return 'File not find!';

    $upload = new \Think\Upload();
    $upload->rootPath  =     './Public/Uploads/';
    
    $info   =   $upload->upload();
    if(!$info) {
        return $upload->getError();
    }else{
        return $info;
    }
}

/**
 * 短信码验证
 * @param   $phone
 * @param   $code
 */
function verify_message_code($phone, $code){
    return S($phone.'_code') == $code;
}

/**
 * CURL请求
 * @param   $url    请求地址
 * @param   $post   传递的POST参数
 * @return  $result 请求结果
 */
// function do_curl($url, $post = null){
//     $ch = curl_init();

//     curl_setopt($ch, CURLOPT_URL, $url);
//     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//     if($post != null){
//         curl_setopt($ch, CURLOPT_POST, 1);
//         curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
//     }

//     $get_content    = curl_exec($ch);
//     curl_close($ch);
//     return $get_content;
// }

function do_curl($url, $data, $cert = false) {
    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //导入证书
    if($cert){
        curl_setopt($ch,CURLOPT_SSLCERT, $cert['ssl_cert']);
        curl_setopt($ch,CURLOPT_SSLKEY,  $cert['ssl_key']);
        curl_setopt($ch,CURLOPT_CAINFO,  $cert['ca_info']);
    }

    $info = curl_exec($ch);

    if (curl_errno($ch)) {
        throw new \Exception(curl_error($ch));
    }

    curl_close($ch);

    return $info;
}

/**
 * 文件下载
 * @param   $file_name  输出文件名
 * @param   $file_src   文件位置
 */
function download_file($file_name, $file_src){
    if(!file_exists($file_src)){
        return 50;
    }

    $file_type  = substr($file_src, strrpos($file_src, '.'));
    $file_size  = filesize($file_src);

    header('Content-type:application/octet-stream');
    header('Content-Disposition:attachment;filename="'.$file_name.'"');
    header("Content-Length:".$file_size);

    $buffer = '';
    $cnt    = 0;

    $handle=fopen($file_src,'rb');
    if($handle===false){
        return false;
    }

    while(!feof($handle)){
        $buffer=fread($handle,1024*1024);
        echo $buffer;
        ob_flush();
        flush();
        if($retbytes){
            $cnt+=strlen($buffer);
        }
    }
    $status=fclose($handle);
    if($retbytes&&$status){
        return $cnt;
    }
    return $status;
}

/**
 * 中文文字截取
 * @param   (string) $string    字符串
 * @param   (int)   $sublen     截取长度
 * @return  （string)    $string
 */
function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
{
    if($code == 'UTF-8'){
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);

        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
        return join('', array_slice($t_string[0], $start, $sublen));
    }else{
        $start = $start*2;
        $sublen = $sublen*2;
        $strlen = strlen($string);
        $tmpstr = '';

        for($i=0; $i< $strlen; $i++)
        {
            if($i>=$start && $i< ($start+$sublen))
            {
                if(ord(substr($string, $i, 1))>129)
                {
                    $tmpstr.= substr($string, $i, 2);
                }
                else
                {
                    $tmpstr.= substr($string, $i, 1);
                }
            }
            if(ord(substr($string, $i, 1))>129) $i++;
        }
        if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";
        return $tmpstr;
    }
}

/**
 * Base64字符串加密
 * @param   string  $text     加密字符串
 * @param   string  $key    加密键值
 * @return  string  $encryptString
 */
function encrypt_text($text, $key = null){
    $key = $key === null ? C('DATA_AUTH_KEY') : $key;
    $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
    $encryptText = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
    return trim(base64_encode($encryptText));
}

/**
 * Base64字符串解密
 * @param  string   $encryptText  密文
 * @param  string   $key 键值
 * @param  string   $string
 */
function decrypt_text($encryptText, $key = null){
    $key = $key === null ? C('DATA_AUTH_KEY') : $key;
    $cryptText = base64_decode($encryptText);
    $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
    $decryptText = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cryptText, MCRYPT_MODE_ECB, $iv);
    return trim($decryptText);
}

/**
*   将数组转换为xml
*    @param array $data    要转换的数组
*   @param bool $root     是否要根节点
*   @return string         xml字符串
*    @author Dragondean
*    @url    http://www.cnblogs.com/dragondean
*/
function arr2xml($data, $root = true){
    $xml    = '';
    if($root) 
        $xml    .= '<xml>';

    foreach($data as $key => $val){
        if(is_array($val)){
            $child  = arr2xml($val, false);
            $xml    .= sprintf("<%s>%s</%s>", $key, $child, $key);
        }else{
            $xml    .= sprintf("<%s><![CDATA[%s]]></%s>", $key, $val, $key);        }
    }
    if($root) 
        $xml .= "</xml>";
    return $xml;
}

function write_log($logPath, $title, $content){
    if(is_array($content))
        $content    = json_encode($content);
    $log    = sprintf(
        "Time:\t[%s]\nTitle:\t%s\nContent:\t%s\n\n\n",
        date('Y-m-d H:i:s'),
        $title,
        $content
    );

    return file_put_contents($logPath, $log, FILE_APPEND);
}
